<template>
    <view class="popcontent" v-if="isonup">
        <view class="popcontent_top">
            <image class="popcontent_img" :src="mainImg" /><view class="popcontent_detail">
                <view v-if="props.from === 'integral'" class="group_price">
                    <template v-if="!goodsDetail.cartDetail.skuId">
                        <text class="hotitem_color" v-if="minPoint">
                            <!-- <text class="jifen">￥</text> -->
                            <text class="popcontent_money">{{ minPointArr[0] }}</text>
                            <text class="price-dian" v-if="minPointArr[1]">.{{ minPointArr[1] }}</text>
                            <text class="add" style="">+</text>
                        </text>
                        <text class="hotitem_color">
                            <text class="popcontent_money">{{ minMoneyArr[0] }}</text>
                            <text class="price-dian" v-if="minMoneyArr[1]">.{{ minMoneyArr[1] }}</text>
                        </text>
                        <!-- <template v-if="!minPoint && minMoney != maxMoney">
                            <view class="fengefu"> ~ </view>
                            <view class="hotitem_color">
                                <text class="popcontent_money">{{ maxMoneyArr[0] }}</text>
                                <text class="price-dian" v-if="maxMoneyArr[1]">.{{ maxMoneyArr[1] }}</text>
                            </view>
                        </template> -->
                    </template>
                    <view v-else>
                        <text class="hotitem_color" v-if="point">
                            <text class="jifen">￥</text>
                            <text class="popcontent_money">{{ pointArr[0] }}</text>
                            <text class="price-dian" v-if="pointArr[1]">.{{ pointArr[1] }}</text>
                            <text class="add" style="margin: 0 7rpx">+</text>
                        </text>
                        <text class="hotitem_color">
                            <text class="popcontent_money">{{ moneyArr[0] }}</text>
                            <text class="price-dian" v-if="moneyArr[1]">.{{ moneyArr[1] }}</text>
                        </text>
                    </view>
                    <view class="jifen">积分</view>
                </view>
                <view v-else-if="props.type == 3" class="group_price">
                    <template
                        v-if="
                            !goodsDetail.cartDetail.skuId ||
                            (goodsDetail.param?.activity?.activityType === 5 && !ladderObj.spellNum)
                        ">
                        <!-- 阶梯拼团需要选择阶梯才展示具体价格 -->
                        <view class="hotitem_color">
                            <text class="price-qian">￥</text>
                            <text class="popcontent_money">{{ minMoneyArr[0] }}</text>
                            <text class="price-dian" v-if="minMoneyArr[1]">.{{ minMoneyArr[1] }}</text>
                        </view>
                        <template v-if="minMoney != maxMoney">
                            <view class="fengefu"> ~ </view>
                            <view class="hotitem_color">
                                <text class="price-qian">￥</text>
                                <text class="popcontent_money">{{ maxMoneyArr[0] }}</text>
                                <text class="price-dian" v-if="maxMoneyArr[1]">.{{ maxMoneyArr[1] }}</text>
                            </view>
                        </template>
                    </template>
                    <view v-else class="hotitem_color">
                        <text class="price-qian">￥</text>
                        <text class="popcontent_money">{{ moneyArr[0] }}</text>
                        <text class="price-dian" v-if="moneyArr[1]">.{{ moneyArr[1] }}</text>
                    </view>
                    <view class="biaoshi"> 拼团价</view>
                </view>
                <view v-else class="hotitem_color">
                    <text class="price-qian">￥</text>
                    <text class="popcontent_money">{{ moneyArr[0] }}</text>
                    <text class="price-dian" v-if="moneyArr[1]">.{{ moneyArr[1] }} </text>
                </view>
                <text class="popcontent_count"> 剩余{{ getStock }}件 </text>
                <text class="popcontent_count">{{ getInformation }}</text>
            </view>
        </view>
        <view>
            <scroll-view
                scroll-top="scrollTop"
                scroll-y="true"
                class="scroll"
                @scrolltoupper="upper"
                @scrolltolower="lower"
                @scroll="scroll">
                <view v-for="(item, index) in goodsDetail.param.goodsSpecList" :key="index" style="padding: 0 28rpx">
                    <view class="popcontent_value">{{ item.attributeKey }}</view>
                    <view class="popcontent_list">
                        <view
                            class="popcontent_all"
                            v-for="(items, indexs) in item.specValueList"
                            :key="indexs"
                            @click="choose(index, indexs, items)">
                            <image
                                class="popcontent_circle"
                                :src="getImgOssUrl('/ui-prod-2.14.0/shouqing.png')"
                                v-show="items.is_showqing == 0 && goodsDetail.param.onSale != 2">
                            </image>
                            <button
                                :disabled="items.is_showqing == 0"
                                :class="
                                    items.is_showqing == 0
                                        ? 'popcontent_btn  disabled_btn'
                                        : items.select
                                        ? 'popcontent_btn  popcontent_redbtn'
                                        : 'popcontent_btn'
                                ">
                                {{ items.attributeValue }}
                            </button>
                        </view>
                    </view>
                </view>
                <view
                    style="padding: 0 28rpx"
                    v-if="
                        goodsDetail.param?.activity?.activityType === 5 &&
                        props.activityStatus === 2 &&
                        props.type == 3 &&
                        !props.spellTotalNum
                    ">
                    <view class="popcontent_value">拼团类型</view>
                    <view class="popcontent_list">
                        <view v-if="!goodsDetail?.cartDetail?.skuId" class="no_select_spe">
                            请先选择
                            <text v-for="eleme in goodsDetail.param.goodsSpecList" :key="eleme.attributeKey">
                                {{ eleme.attributeKey }}
                            </text>
                        </view>
                        <button
                            v-else
                            v-for="(items, indexs) in ladderObj.threeSpeArr"
                            :key="indexs"
                            @click="chooseLadderItem(items, indexs)"
                            :class="items.select ? 'popcontent_btn  popcontent_redbtn' : 'popcontent_btn'">
                            ￥{{ items.price }}/{{ items.ladder }}人团
                        </button>
                    </view>
                </view>
                <view class="popcontent_stepcount">
                    <div class="popcontent_stepcount_left">
                        <text>购买数量</text>
                    </div>
                    <div class="popcontent_stepcount_right">
                        <view class="popcontent_stepcount_right_desc">{{ getPurchaseLimit() }}</view>
                        <uni-number-box
                            :min="1"
                            :max="maxStock"
                            v-model="goodsDetail.cartDetail.quantity"
                            :disabled="goodsDetail.param.onSale == 2" />
                    </div>
                </view>
            </scroll-view>
        </view>
        <div v-if="goodsDetail.param.onSale == 2" class="fixed">
            <view class="popcontent_pay">
                <button class="twobutton otherbth btn disabled">已下架</button>
            </view>
        </div>
        <div v-else-if="getGoodsStatus(goodsDetail.param)" class="fixed">
            <view class="popcontent_pay">
                <button class="twobutton otherbth btn disabled">已售罄</button>
            </view>
        </div>
        <div
            v-else-if="props.type === 2 && goodsDetail.param.activity?.activityStatusName?.realStatus === 3"
            class="fixed">
            <view class="popcontent_pay">
                <button class="twobutton otherbth btn disabled">活动已结束</button>
            </view>
        </div>
        <div
            v-else-if="
                props.activityId &&
                props.activityStatus != 1 &&
                goodsDetail.param.activity?.activityType == 2 &&
                props.type == 2
            "
            class="fixed">
            <view class="popcontent_pay">
                <button @touchstart.stop="buyGoods" class="twobutton btn otherbth">立即抢购</button>
            </view>
        </div>
        <div
            v-else-if="
                props.activityId &&
                props.activityStatus != 1 &&
                goodsDetail.param.activity?.activityType >= 3 &&
                props.type == 3
            "
            class="fixed">
            <view class="popcontent_pay">
                <button @touchstart.stop="buyGoods" class="twobutton btn otherbth">下一步</button>
            </view>
        </div>
        <div v-else class="fixed">
            <template v-if="props.from === 'integral'">
                <view v-if="!goodsDetail.param.isPointsGood" class="popcontent_pay">
                    <button class="twobutton otherbth btn disabled">兑换已结束</button>
                </view>
                <view v-else-if="goodsDetail.param.onSale == 2" class="popcontent_pay">
                    <button class="twobutton otherbth btn disabled">商品已失效</button>
                </view>
                <view v-else-if="getStock < 1" class="popcontent_pay">
                    <button class="twobutton otherbth btn disabled">商品已兑完</button>
                </view>
                <view
                    v-else-if="
                        (getStock > 0 && !isToken) ||
                        (getStock > 0 && props.points >= money * goodsDetail.cartDetail.quantity) ||
                        (getStock > 0 &&
                            props.points >= money * goodsDetail.cartDetail.quantity &&
                            !goodsDetail.cartDetail.skuId)
                    "
                    class="popcontent_pay">
                    <button @touchstart.stop="buyGoods" class="twobutton otherbth btn">立即兑换</button>
                </view>
                <view v-else class="popcontent_pay">
                    <button class="twobutton otherbth btn disabled">积分不足</button>
                </view>
            </template>
            <template v-else>
                <view class="popcontent_pay" v-if="props.specValueList">
                    <button @touchstart.stop="addgoods" class="twobutton otherbth btn">确认</button>
                </view>
                <view class="popcontent_pay" v-else>
                    <button @touchstart.stop="addgoods" class="btn">加入购物车</button>
                    <button @touchstart.stop="buyGoods" class="twobutton btn">立即购买</button>
                </view>
            </template>
        </div>
    </view>
</template>
<script setup>
import { ref, reactive, computed, onMounted, watch, inject } from 'vue';
import request from '@/request';
import storage from '@/commons/storage';
import { useTrace } from '@/commons/trace';
import shopingGoodsSteps from '@/components/shopingGoodsSteps';
import { getImgOssUrl } from '@/commons/utils.js';
import { floatDivide, checkToken } from '@/commons/utils.js';
import router from '@/router';

const { traceReport } = useTrace({ autoLoad: false });
const emit = defineEmits(['close', 'getskuvalue', 'updata', 'buyGoods', 'popup']);
const sku_information = ref('');
const mainImg = ref('');
let skuidData = reactive({}); //记录初始化页面时的数据skuSepcList
const chooseItem = ref([]); //记录已选中的规格值
const getStock = ref(0); //库存量
const activityStock = ref(0); //活动库存
const maxStock = ref(1);
const money = ref(''); //价格
const minMoney = ref(''); //最低价格
const maxMoney = ref(''); //最高价格
const minPoint = ref('');
const point = ref('');
const isonup = ref(false);
const currency = inject('currency');
let isToken = ref();
const minMoneyArr = computed(() => {
    return minMoney.value.toString().split('.');
});
const minPointArr = computed(() => {
    return minPoint.value.toString().split('.');
});
const maxMoneyArr = computed(() => {
    return maxMoney.value.toString().split('.');
});
const moneyArr = computed(() => {
    return money.value.toString().split('.');
});
const pointArr = computed(() => {
    return point.value.toString().split('.');
});
let goodsDetail = reactive({
    param: {
        goodsSpecList: [],
        skuSepcList: {},
        activity: {},
        materialList: [],
        skuList: [],
        specValueList: [],
        onSale: 1
    },
    cartDetail: { skuId: '', goodsId: '', quantity: 1 }
});
const state = reactive({
    currentCoverUrl: '', // 当前封面图
    currentCoverIndex: 0, // 当前封面图索引
    materialList: [] // 封面图列表
});
const getPurchaseLimit = () => {
    if (props.from === 'integral') {
        // gooods
        // maxBuyerCount
        if (goodsDetail.param.maxBuyerCount > 0) {
            return `每单最多可兑换${goodsDetail.param.maxBuyerCount}件`;
        }
    }
    if (props.type != 1) {
        if (props.activityId && props.activityStatus != 1) {
            if (goodsDetail.param.activity?.activityType == 2 && goodsDetail.param.activity.purchaseLimit > 0) {
                return `*限购${goodsDetail.param.activity.purchaseLimit}件`;
            }
            if (
                (goodsDetail.param.activity.activityType >= 3 && goodsDetail.param.activity.purchaseLimit > 0) ||
                goodsDetail.param.activity.orderPurchaseLimit > 0
            ) {
                return `*限购${
                    goodsDetail.param.activity.orderPurchaseLimit || goodsDetail.param.activity.purchaseLimit
                }件`;
            }
        }
    }
    return '';
};
const getInformation = computed(() => {
    emit('getskuvalue', sku_information.value);
    return sku_information.value ? '已选：' + sku_information.value : '暂无';
});

const ladderObj = reactive({
    spellNum: 0,
    allThreeSpeArr: [],
    threeSpeArr: []
});

const props = defineProps({
    shopId: {},
    goodsId: { required: true },
    goodsNo: {},
    show: {},
    specValueList: {},
    coverSrc: {},
    skuId: {},
    cartId: {},
    quantity: {},
    isvalid: {},
    activityId: {},
    activityStatus: {},
    type: { type: Number, default: 1 },
    from: {},
    points: {},
    spellTotalNum: { type: Number, default: 0 }
});
const onDivide = v => currency(v).divide(100).value;
onMounted(() => {});
// 数据升序处理
const upwardData = data => {
    data.sort((a, b) => {
        return a.sort - b.sort;
    });
};
// 获取已选规格
const getconcatparam = () => {
    const concatData = [];
    goodsDetail.param.goodsSpecList.map(item => {
        item['specValueList']?.map(items => {
            if (items.select) {
                concatData.push(items.attributeValue);
                return;
            }
        });
    });
    return concatData;
};
/**初始化按钮：flag：是否初始化回显选中规格值 */
const createBtn = flag => {
    //判断所有规格值的状态
    goodsDetail.param.specValueList?.map(item => {
        // 回显选中的规格值
        if (props.specValueList && props.isvalid && flag) {
            let attributeValueId = props.specValueList.map(item => item.attributeValueId);
            if (attributeValueId.includes(item.attributeValueId)) {
                item.select = true;
            }
        }
        // 判断初始化规格值是否售罄
        for (let key in goodsDetail.param.skuSepcList) {
            // select:false默认未选中
            var skuList = key.split(';');
            if (skuList.includes(item.attributeValue) && goodsDetail.param.skuSepcList[key] != 0) {
                item.is_showqing = 1;
                break;
            } else if (skuList.includes(item.attributeValue) && goodsDetail.param.skuSepcList[key] == 0) {
                item.is_showqing = 0;
            }
        }
    });
    // 回显选中的规格值
    if (props.specValueList && props.isvalid && flag) {
        goodsDetail.cartDetail.skuId = skuidData[sku_information.value];

        let attributeId = props.specValueList?.map(item => item.attributeId);
        goodsDetail.param.goodsSpecList.map((item, index) => {
            if (attributeId.includes(item.attributeId)) {
                chooseItem.value[index] = props.specValueList[index]?.attributeValue;
            }
        });
        sku_information.value = getconcatparam().join(';');
        goodsDetail.param.skuList.map(value => {
            if (value.skuId == skuidData[sku_information.value]) {
                money.value = currency(value.skuPrice).divide(100).value;
                mainImg.value = value.skuImg || state.currentCoverUrl;
                if (props.from === 'integral') {
                    money.value = currency(value.consumerPoints).divide(100).value;
                    point.value = currency(value.money).divide(100).value;
                }
            }
        });
        goodsDetail.cartDetail.quantity = props.quantity;
        getStock.value = goodsDetail.param.skuSepcList[sku_information.value];
        goodsDetail.cartDetail.skuId = skuidData[sku_information.value];
        // xxxxx
        // goodsDetail.param.activity.spellActivityPrice.forEach(item => {
        //     if (item.skuId == skuidData[sku_information.value]) {
        //         money.value = item.spellPrice;
        //     }
        // });
    }
};
const getSkuList = () => {
    upwardData(goodsDetail.param.materialList);
    upwardData(goodsDetail.param.goodsSpecList);
    // upwardData(goodsDetail.param.specValueList);
    upwardData(goodsDetail.param.materialList);
    goodsDetail.param.specValueList.map((value, index) => {
        goodsDetail.param.specValueList[index] = { ...value, is_showqing: 1, select: false };
    });
    // 处理规格和规格值数据,可以循环展示
    goodsDetail.param.goodsSpecList.forEach((items, index) => {
        const data = goodsDetail.param.specValueList.filter(value => {
            return items.attributeId == value.attributeId;
        });
        const attrName = [];
        const attrData = [];
        data.map(value => {
            if (!attrName.includes(value.attributeValue)) {
                attrName.push(value.attributeValue);
                attrData.push(value);
            }
        });
        goodsDetail.param.goodsSpecList[index] = { ...items, specValueList: attrData };
    });
    // 初始化图片，展示封面图
    mainImg.value = state.currentCoverUrl;
    // 处理ku_sepc_list:'黄色;6.2寸':sku_id==>'黄色;6.2寸':库存量
    for (let key in goodsDetail.param.skuSepcList) {
        let skuid = goodsDetail.param.skuList.filter(value => {
            return goodsDetail.param.skuSepcList[key] == value.skuId;
        });
        goodsDetail.param.skuSepcList[key] = skuid[0].skuStock;
    }
    createBtn(true);
    sku_information.value = getconcatparam().join(';');
    isonup.value = true;
    emit('popup');
};
//点击或取消点击事件
const choose = (val, value, items) => {
    //售罄不允许点击
    if (items.is_showqing == 0) {
        return;
    }
    // 控制规格按钮的选中
    const currentSelect = goodsDetail.param.goodsSpecList[val]['specValueList'][value].select;
    goodsDetail.param.goodsSpecList[val]['specValueList'].forEach(item => (item.select = false));
    goodsDetail.param.goodsSpecList[val]['specValueList'][value].select = !currentSelect;
    var concatparam = goodsDetail.param.goodsSpecList[val]['specValueList'][value].attributeValue;
    sku_information.value = getconcatparam().join(';');
    // 记录已选择规格值
    if (!currentSelect) {
        chooseItem.value[val] = concatparam;
    } else {
        chooseItem.value[val] = '';
    }

    // 根据规格值的选择动态匹配库存和价格
    let chooseskuValue = chooseItem.value.filter(item => item.trim());
    if (chooseskuValue.length == goodsDetail.param.goodsSpecList.length) {
        if (!props.specValueList) {
            // 详情页每次切换规格值数量都要充值1
            goodsDetail.cartDetail.quantity = 1;
        }
        getStock.value = goodsDetail.param.skuSepcList[sku_information.value];
        goodsDetail.param.skuList.map(value => {
            if (value.skuId == skuidData[sku_information.value]) {
                //阶梯拼团这个节点不显示价格
                if (goodsDetail.param?.activity?.activityType !== 5 || props.type === 1) {
                    money.value = currency(value.skuPrice).divide(100).value;
                }
                mainImg.value = value.skuImg || state.currentCoverUrl;
                if (props.from === 'integral') {
                    money.value = currency(value.consumerPoints).divide(100).value;
                    point.value = currency(value.money).divide(100).value;
                }
            }
        });
        goodsDetail.cartDetail.skuId = skuidData[sku_information.value];
        if (props.type == 3 && goodsDetail.cartDetail.skuId && goodsDetail.param?.activity?.activityType === 5) {
            const activityInfo = ladderObj.allThreeSpeArr.find(x => x.skuId === goodsDetail.cartDetail.skuId) || {};
            ladderObj.threeSpeArr = [];
            const ladderArr = Object.keys(activityInfo.skuSpellInfo) || [];
            ladderArr.forEach(x => {
                ladderObj.threeSpeArr.push({
                    ladder: x,
                    price: currency(activityInfo.skuSpellInfo[x]).divide(100).value
                });
            });
            if (!props.spellTotalNum) {
                ladderObj.spellNum = '';
            } else {
                // 参加别人的团，默认选中了拼团类型
                let item = ladderObj.threeSpeArr.find(e => e.ladder == props.spellTotalNum);
                // item.select = true;
                money.value = item.price;
            }
        }
    } else {
        goodsDetail.cartDetail.skuId = '';
        getStock.value = goodsDetail.param.goodsStock;
        mainImg.value = state.currentCoverUrl;
        money.value = minMoney.value;
        if (goodsDetail.param?.activity?.activityType == 2 && props.activityStatus != 1) {
            getStock.value = activityStock.value;
        }
    }
    createBtn(false);
    chooseItem.value.forEach(item => {
        const match_data = [];
        if (item) {
            for (let key in goodsDetail.param.skuSepcList) {
                let skuList = key.split(';');
                if (skuList.includes(item)) {
                    // 获取匹配规格值的skuSepcList
                    const param = {};
                    param[key] = goodsDetail.param.skuSepcList[key];
                    match_data.push(param);
                }
            }
            getBtnStatus(match_data);
        }
    });
};
// 判断按钮是否可选，不可选置灰
const getBtnStatus = keyArray => {
    goodsDetail.param.goodsSpecList.forEach((item, index) => {
        item.specValueList?.map(items => {
            let num = 0;
            let showqing_num = 0;
            if (!items.select) {
                // 遍历匹配规格值的数组
                try {
                    keyArray.map(value => {
                        for (let key in value) {
                            var skuList = key.split(';');
                            if (skuList.includes(items.attributeValue)) {
                                num++;
                                const param = JSON.parse(JSON.stringify(chooseItem.value));
                                param[index] = items.attributeValue;
                                if (value[key] == 0) {
                                    if (param.join(';') == key) {
                                        items.is_showqing = 0;
                                        throw Error;
                                    }
                                }
                                if (value[key] == 1) {
                                    items.is_showqing = 1;
                                } else if (value[key] == 0) {
                                    showqing_num++;
                                }
                            }
                        }
                    });
                    if (showqing_num == num && showqing_num) {
                        items.is_showqing = 0;
                    }
                } catch {
                    return;
                }
            }
        });
    });
};

// 选择阶梯拼团拼团类型
const chooseLadderItem = (item, idx) => {
    ladderObj.threeSpeArr.map(x => {
        x.ladder === item.ladder ? (x.select = !x.select) : (x.select = false);
    });
    money.value = item.price;
    ladderObj.spellNum = item.select ? item.ladder : '';
    emit('getSpellNum', { num: ladderObj.spellNum });
};
/** 添加购物车*/
const addgoods = async () => {
    if (goodsDetail.param.onSale !== 1) {
        uni.showToast({
            title: '商品已失效，去看看其他商品吧',
            icon: 'none'
        });
        return;
    }
    let chooseskuValue = chooseItem.value.filter(item => item.trim());
    if (!chooseskuValue.length && goodsDetail.param.goodsSpecList.length) {
        uni.showToast({
            title: '请选择规格',
            icon: 'none'
        });
    } else if (chooseskuValue.length == goodsDetail.param.goodsSpecList.length) {
        //修改购物车
        if (props.specValueList) {
            const { goodsId, cartId } = props;
            request('cartUpdateServ', {
                goodsId,
                quantity: goodsDetail.cartDetail.quantity,
                cartId,
                skuId: goodsDetail.cartDetail.skuId
            }).then(res => {
                uni.showToast({
                    title: '修改成功！',
                    icon: 'none'
                });
                emit('close');
                emit('updata');
            });
        } else {
            //添加购物车
            goodsDetail.cartDetail.goodsId = props.goodsId;
            traceReport('add_cart', {
                productId: goodsDetail.cartDetail.goodsId,
                productName: goodsDetail.param.goodsName,
                skuId: goodsDetail.cartDetail.skuId,
                skuName: sku_information.value,
                num: goodsDetail.cartDetail.quantity
            });
            if (!(await checkToken())) {
                emit('close', { quantity: 0 });
            }
            request(
                'cartAddServ',
                props.activityId ? { ...goodsDetail.cartDetail, activityId: props.activityId } : goodsDetail.cartDetail
            )
                .then(res => {
                    uni.showToast({
                        title: '添加成功',
                        icon: 'none'
                    });
                    emit('close', { quantity: goodsDetail.cartDetail.quantity });
                })
                .catch(err => {
                    uni.showToast({
                        title: err.data.msg,
                        icon: 'none'
                    });
                    // 重新加载数据
                    getDetail();
                    emit('updata');
                });
        }
    } else {
        uni.showToast({
            title: `请选择${goodsDetail.param.goodsSpecList[chooseItem.value.indexOf('')].attributeKey}`,
            icon: 'none'
        });
    }
};

const buyGoods = async () => {
    let chooseskuValue = chooseItem.value.filter(item => item.trim());
    if (!chooseskuValue.length && goodsDetail.param.goodsSpecList.length) {
        uni.showToast({
            title: '请选择规格',
            icon: 'none'
        });
    } else if (ladderObj.threeSpeArr?.length && !ladderObj.spellNum && props.type == 3) {
        uni.showToast({
            title: '请选择拼团类型',
            icon: 'none'
        });
    } else if (chooseskuValue.length == goodsDetail.param.goodsSpecList.length) {
        if (!(await checkToken())) {
            emit('close', { quantity: 0 });
        }
        goodsDetail.cartDetail.goodsId = props.goodsId;
        traceReport('place_order', {
            productId: props.goodsId,
            productName: goodsDetail.param.goodsName,
            skuId: goodsDetail.cartDetail.skuId,
            skuName: sku_information.value,
            num: goodsDetail.cartDetail.quantity
        });
        emit('buyGoods', goodsDetail.cartDetail);
    } else {
        uni.showToast({
            title: `请选择${goodsDetail.param.goodsSpecList[chooseItem.value.indexOf('')].attributeKey}`,
            icon: 'none'
        });
    }
};

// 参与阶梯拼团时获取价格范围
const rebuildLadderPrice = arr => {
    const allSkuPrice = Array.from(ladderObj.allThreeSpeArr, x => x.skuSpellInfo);
    let allPriceObj = {};
    arr.map(x => {
        allPriceObj[x] = [];
    });
    arr.forEach(x => {
        allSkuPrice.forEach(item => {
            item[x] ? allPriceObj[x].push(item[x]) : '';
        });
    });
    arr.map(x => {
        allPriceObj[x].sort((a, b) => {
            return a - b;
        });
    });
    minMoney.value = currency(allPriceObj[props.spellTotalNum][0]).divide(100).value;
    maxMoney.value = currency(allPriceObj[props.spellTotalNum][allPriceObj[props.spellTotalNum].length - 1]).divide(
        100
    ).value;
};

const initData = () => {
    sku_information.value = '';
    mainImg.value = '';
    skuidData = reactive({});
    chooseItem.value = [];
    getStock.value = 0;
    activityStock.value = 0;
    maxStock.value = 1;
    money.value = '';
    minMoney.value = '';
    maxMoney.value = '';
    isonup.value = false;
    state.currentCoverUrl = '';
    state.currentCoverIndex = 0;
    state.materialList.length = 0;
    goodsDetail.cartDetail.quantity = 1;
    goodsDetail.cartDetail.skuId = '';
    goodsDetail.cartDetail.goodsId = '';
    goodsDetail.param.goodsSpecList = [];
    goodsDetail.param.skuSepcList = {};
    goodsDetail.param.activity = {};
    goodsDetail.param.materialList = [];
    goodsDetail.param.skuList = [];
    goodsDetail.param.specValueList = [];
    goodsDetail.param.onSale = 1;
};
// 获取商品详情
const getDetail = async () => {
    initData();
    let params = {
        goodsId: props.goodsId,
        shopId: props.shopId || uni.getStorageSync('ZW_SHOP_ID')
    };
    if (props.goodsNo) {
        params.goodsNo = props.goodsNo;
    }
    if (props.activityId) {
        params.activityId = props.activityId;
        if (props.type == 2 && props.activityStatus == 1) delete params.activityId;
    }
    if (props.from === 'integral') {
        params.isPointsGood = 1;
    }
    try {
        const res = await request('goodsDetailServ', params);
        state.materialList = res.data.materialList || [];
        state.currentCoverIndex = state.materialList.findIndex(item => item?.isCover === 1);
        state.currentCoverIndex = state.currentCoverIndex === -1 ? 0 : state.currentCoverIndex;
        state.currentCoverUrl = state.materialList[state.currentCoverIndex]?.materialSrc;
        // 已下架商品清空库存
        if (res.data.onSale === 2) {
            res.data.skuList = res.data.skuList.map(item => {
                item.skuStock = 0;
                return item;
            });
        }
        // 积分商品库存设置
        if (props.from === 'integral') {
            let pointsStock = 0;
            res.data.skuList = res.data.skuList.map(item => {
                if (item.consumerPoints === null) {
                    item.skuStock = 0;
                }
                pointsStock += item.skuStock;
                return item;
            });
            res.data.goodsStock = pointsStock;
        }
        goodsDetail.param = Object.assign(goodsDetail.param, res.data);
        skuidData = JSON.parse(JSON.stringify(goodsDetail.param.skuSepcList));
        chooseItem.value = [];
        goodsDetail.param.goodsSpecList.forEach(item => {
            chooseItem.value.push('');
        });
        getStock.value = goodsDetail.param.goodsStock;
        money.value = currency(goodsDetail.param.goodsMinPrice).divide(100).value;
        minMoney.value = currency(goodsDetail.param.goodsMinPrice).divide(100).value;
        maxMoney.value = currency(goodsDetail.param.goodsMaxPrice).divide(100).value;
        // 积分商品;
        if (props.from === 'integral') {
            let sortArr = goodsDetail.param.skuList
                .filter(item => item.consumerPoints !== null)
                .sort((a, b) => a.consumerPoints - b.consumerPoints);
            let pointArr = goodsDetail.param.skuList
                .filter(item => item.skuPrice !== null)
                .sort((a, b) => a.skuPrice - b.skuPrice);
            money.value = onDivide(sortArr[0].consumerPoints);
            minMoney.value = onDivide(sortArr[0].consumerPoints);
            maxMoney.value = onDivide(sortArr[sortArr.length - 1].consumerPoints);
            point.value = onDivide(pointArr[0].money);
            minPoint.value = onDivide(pointArr[0].money);
            minMoney.value = onDivide(pointArr[0].consumerPoints);
        }
        if (props.type != 1) {
            // 秒杀
            if (goodsDetail.param?.activity?.activityType == 2) {
                if (props.activityStatus != 1 && props.activityId) {
                    let sortArr = goodsDetail.param.activity.activityGoods.sort((a, b) => a.spikePrice - b.spikePrice);
                    minMoney.value = currency(sortArr[0].spikePrice).divide(100).value;
                    maxMoney.value = currency(sortArr[sortArr.length - 1].spikePrice).divide(100).value;
                    money.value = currency(sortArr[0].spikePrice).divide(100).value;
                    activityStock.value = goodsDetail.param.activity.activityGoods.reduce(
                        (pre, cur) => pre + +cur.spikeStockSurplus,
                        0
                    );
                    getStock.value = activityStock.value;
                }
            }
            // 拼团
            if (goodsDetail.param?.activity?.activityType === 5) {
                ladderObj.allThreeSpeArr = res.data?.activity?.spellActivityPrice || [];
                minMoney.value = currency(goodsDetail.param.activity?.spellActivityGroupInfo?.minPrice).divide(
                    100
                ).value;
                maxMoney.value = currency(goodsDetail.param.activity?.spellActivityGroupInfo?.maxPrice).divide(
                    100
                ).value;
                money.value = currency(goodsDetail?.param.goodsMinPrice).divide(100).value;
                // 参与阶梯拼团
                if (props.spellTotalNum) {
                    ladderObj.spellNum = props.spellTotalNum;
                    rebuildLadderPrice(res.data?.activity?.spellActivityGroupInfo?.requiredNum);
                }
            } else if (goodsDetail.param?.activity?.activityType >= 3) {
                if (props.activityStatus != 1 && props.activityId) {
                    let sortArr = goodsDetail.param.activity.spellActivityPrice.sort(
                        (a, b) => a.spellPrice - b.spellPrice
                    );
                    minMoney.value = currency(sortArr[0].spellPrice).divide(100).value;
                    maxMoney.value = currency(sortArr[sortArr.length - 1].spellPrice).divide(100).value;
                    money.value = currency(sortArr[0].spellPrice).divide(100).value;
                }
            }
        }
        getSkuList();
    } catch (error) {
        emit('close');
    }
};
//判断商品售罄状态（两种：秒杀和其他商品）
const getGoodsStatus = item => {
    // 判断商品状态（秒杀和其他商品不同，其他商品onSale==3就是售罄状态，秒杀商品库存是预占的需要判断spike_stock_surplus）
    if (item.activity?.id && item.activity?.activityType == 2) {
        let total = 0;
        (item.activity?.activityGoods || []).forEach(value => {
            total += Number(value.spikeStockSurplus);
        });
        return total > 0 ? false : true;
    } else {
        return item.onSale == 3;
    }
};
watch(
    () => props.show,
    async val => {
        if (val) {
            isToken.value = await checkToken();
            if (!isToken.value) {
                router.push('/pages-user/login/index');
                return;
            }
            getDetail();
        } else {
            isonup.value = false;
        }
    }
);
// todo：这个可以不要？
watch(
    () => goodsDetail.cartDetail.skuId,
    v => {
        if (props.type != 1 && props.activityStatus != 1) {
            if (goodsDetail.param.activity?.activityType == 2) {
                let findItem = goodsDetail.param.activity.activityGoods.find(item => item.skuId == v);
                if (findItem) {
                    getStock.value = findItem.spikeStockSurplus;
                    money.value = currency(findItem.spikePrice).divide(100).value;
                }
            }
            if (goodsDetail.param.activity?.activityType >= 3) {
                let findItem = goodsDetail.param.activity.spellActivityPrice.find(item => item.skuId == v);
                if (findItem) {
                    //阶梯拼团不显示价格
                    if (goodsDetail.param?.activity?.activityType !== 5) {
                        money.value = currency(findItem.spellPrice).divide(100).value;
                    }
                }
            }
        }
    }
);

watch(getStock, v => {
    if (props.type != 1) {
        if (props.activityId && props.activityStatus != 1) {
            if (
                goodsDetail.param?.activity?.activityType == 2 &&
                v > goodsDetail.param.activity?.purchaseLimit &&
                goodsDetail.param.activity?.purchaseLimit > 0
            ) {
                maxStock.value = goodsDetail.param.activity.purchaseLimit;
            } else if (goodsDetail.param?.activity?.activityType >= 3) {
                if (v > goodsDetail.param.activity.orderPurchaseLimit || v > goodsDetail.param.activity.purchaseLimit) {
                    maxStock.value =
                        goodsDetail.param.activity.orderPurchaseLimit || goodsDetail.param.activity.purchaseLimit || v;
                } else {
                    maxStock.value = v;
                }
            } else {
                maxStock.value = v;
            }
        } else {
            maxStock.value = v;
        }
    } else {
        if (props.from === 'integral') {
            maxStock.value =
                goodsDetail.param.maxBuyerCount > 0 && goodsDetail.param.maxBuyerCount < v
                    ? goodsDetail.param.maxBuyerCount
                    : v;
        } else {
            maxStock.value = v;
        }
    }
});
</script>
<style lang="scss" scoped src="./index.scss"></style>
